package com.sdp.right.dr;

import java.lang.reflect.Method;
import java.util.List;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.sdp.core.bizc.annotation.Dr;
import com.sdp.core.bizc.threadLocal.ContextManager;
import com.sdp.core.bizc.utils.CoreConstantsEnum;
import com.sdp.core.bizc.vo.DataCenter;
import com.sdp.right.cache.keys.RightCacheKeys;
import com.sdp.right.db.sys_dict.service.ISysDictService;


@Aspect
@Component
@Order(1)
public class DrAspect {
	
	
	@Autowired
	private DrFilter drFilter;
	
	@Autowired
	private ISysDictService iSysDictService;
	
	@Pointcut("@annotation(com.sdp.core.bizc.annotation.Dr)")
	public void drCut() {}
	

	@Before(value="drCut()")
	public void dr(JoinPoint joinPoint) {
		
		// 从切面织入点处通过反射机制获取织入点处的方法
		MethodSignature signature = (MethodSignature) joinPoint.getSignature();
		// 获取切入点所在的方法
		Method method = signature.getMethod();
		Dr dr = method.getAnnotation(Dr.class);
		if(dr ==null) {
			return;
		}
		String drNo = dr.drNo();
		if(StringUtils.isEmpty(drNo)) {
			return;
		}
		
		//获取当前登录人账号
		String accountNo = ContextManager.getContextData(CoreConstantsEnum.token中账号的属性名.getCode());
		if(StringUtils.isEmpty(accountNo)) {
			return;
		}
		
		//获取传入目标方法的参数
        Object[] args = joinPoint.getArgs();
        if(args==null || args.length==0) {
        	return;
        }
        
        DataCenter dc = null;
        for (int i = 0; i < args.length; i++) {
        	if (!args[i].getClass().isPrimitive() && DataCenter.class.getName().equals(args[i].getClass().getName())) {
        		dc = (DataCenter) args[i];
        		break;
        	}
        }
        
        if(dc==null) {
        	return;
        }
        
		//先根据人员数据权限进行过滤，如果人员数据权限没有再根据角色
		//根据人员进行数据权限过滤
		Object drEmpRuleCache = iSysDictService.getDictInfo(RightCacheKeys.DR_EMP_CACHE_KEY, drNo,accountNo);
		if(drEmpRuleCache==null || ((List<?>) drEmpRuleCache).size()==0) {
			//根据角色进行数据过滤
			drFilter.roleFilter(dc, drNo, accountNo);
		}else {
			//根据人员过滤
			drFilter.empFilter(dc, drNo, drEmpRuleCache);
		}
	
	}
	
	
}
